const { Insurances } = require("../models/insuranceModel");

// 查看所有保险产品
async function getInsurance(req, res) {
    const { _id, pageSize = 10, currentPage = 1 } = req.query;

    // 总条数
    const total = await Insurances.countDocuments();

    // 总页数
    const totalPages = Math.ceil(total / pageSize);
    const data = await Insurances
        .find(_id)
        .limit(pageSize - 0)
        .skip((currentPage - 1) * pageSize)
    res.send({
        status: 1,
        data: { total, totalPages, data, pageSize, currentPage },
        message: '获取保险信息成功'
    })
    res.send({
        status: 0,
        message: '获取保险信息失败'
    })
}

//增加保险
async function addInsurance(req, res) {
    const { name, price, payment, duration, insuranceTypeId } = req.body
    console.log(req.body);
    const data = await Insurances.create({ name, price, payment, duration, insuranceTypeId });
    res.send({
        msg: "成功",
        status: 1,
        data: data
    })
}


//通过ID获取保险信息
async function getInsuranceById(req, res) {
    console.log(123, req.body._id);
    try {
        const data = await Insurances.findById(req.body._id)
        res.send({
            status: 1,
            data: data,
            message: '获取保险信息成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            message: '获取保险信息失败'
        })
    }
}

//修改保险产品信息
async function modifyInsurance(req, res) {
    const { _id, name, price, payment, duration } = req.body
    const data = await Insurances.update({ _id }, { name, price, payment, duration })
    console.log(data);
    if (data.nModified == 1) {
        res.send({
            msg: "修改成功",
            data: data,
            status: 1,
        })
    }

}


// 删除保险
async function deleteInsurance(req, res) {
    const { _id } = req.body
    const data = await Insurances.deleteOne({ _id })
    if (data.deletedCount == 1) {
        res.send({
            msg: '删除成功',
            num: 1,
        })
    } else {
        res.send({
            msg: '删除失败',
            num: 0,
        })
    }
}

module.exports = { getInsurance, addInsurance, getInsuranceById, modifyInsurance, deleteInsurance }